/* --------------------------------------------------------------------------------------------
 * Copyright (c) 2024 TypeFox and others.
 * Licensed under the MIT License. See LICENSE in the package root for license information.
 * ------------------------------------------------------------------------------------------ */

import { resolve } from 'node:path'
import { IncomingMessage } from 'node:http'
import { runLanguageServer } from '../common/node/language-server-runner.js'
import { ca } from 'element-plus/es/locales.mjs';
const jwt = require('jsonwebtoken');
// import { LanguageName } from '../common/node/server-commons.js'
const secretKey = "xTclIUMsliCuqadIeN5LdtxP42S19Ig7JE8l--UAEXE"
export enum LanguageName {
  /** https://nodejs.org/api/cli.html  */
  node = 'node',
  /** https://docs.oracle.com/en/java/javase/21/docs/specs/man/java.html */
  java = 'java'
}

export const runPythonServer = (baseDir: string, relativeDir: string) => {
  console.log('Running Python server')
  const processRunPath = resolve(baseDir, relativeDir)
  runLanguageServer({
    serverName: 'PYRIGHT',
    pathName: '/smarttrading/ws/pyright',
    serverPort: 30001,
    runCommand: LanguageName.node,
    runCommandArgs: [processRunPath, '--stdio'],
    wsServerOptions: {
      noServer: true,
      perMessageDeflate: false,
      clientTracking: true,
      verifyClient: (
        clientInfo: { origin: string; secure: boolean; req: IncomingMessage },
        callback
      ) => {
        // throw new Error('Method not implemented.')
        const parsedURL = new URL(`${clientInfo.origin}${clientInfo.req.url ?? ''}`)
        try {
          const authToken = parsedURL.searchParams.get('authorization')
          const decodedPayload = jwt.verify(authToken, secretKey);
          console.log('Decoded payload:', decodedPayload)
          if (Date.now() < decodedPayload.exp) {
            console.log('Token expired') 
            callback(false)
            return
          }
          callback(true)
        }catch (error) {
          console.log('Error:', error)
          callback(false)
        }
      }
    }
  })
}
